﻿using MiniExcelLibs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using yichu_front.BLL;
using yichu_front.Model;

namespace yichu_front
{
    public partial class Form_Main : Form
    {
        TreeNode CurrentNode;//材料分类选中的节点
        private List<BOM_Material_Mapping> BOM_Material_MappingList = new List<BOM_Material_Mapping>();
        private BindingSource bsBOMList = new BindingSource();
        private List<BOMSelected> BOMSelectedList = new List<BOMSelected>();
        private BindingSource bsBOMSelectedList = new BindingSource();
        public Form_Main()
        {
            InitializeComponent();
        }

        private void Form_Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void Form_Main_Load(object sender, EventArgs e)
        {
            showMessageWhenLoad();
            getAllBOMType();
        }
        private void showMessageWhenLoad()
        {
            //查询最新的铜价和调价时间。
            Material cu = SqlSugarHelp.scope.Queryable<Material>().Where(it => it.材料名称 == "实时铜价").OrderBy(it => it.修改时间).First(); 
            if (cu != null)
            {
                this.txt_lastCuPrice.Text = cu.材料单价.ToString();
                this.txt_LastCuTime.Text = cu.修改时间.ToString();
            }
            //查询最新通告

            // 展示最新的公告
            Notice notice = SqlSugarHelp.scope.Queryable<Notice>().OrderBy(it => it.通告时间, SqlSugar.OrderByType.Desc).First();
            if (notice != null)
            {
                this.txt_notice.Text = notice.通告内容;
            }
        }
        /// <summary>
        /// 查询所有型号分类
        /// </summary>
        private void getAllBOMType()
        {
            //添加后刷新会重复添加，先清空
            this.tree_BOMType.Nodes.Clear();
            List<BOMType> BOMTypes = SqlSugarHelp.scope.Queryable<BOMType>().ToTree(it => it.Child, it => it.parentId, 0);
            //加载分类
            LoadTreeView(this.tree_BOMType.Nodes, BOMTypes);
        }

        #region 左侧树加载
        /// <summary>
        /// 加载型号分类TreeView
        /// </summary>
        /// <param name="treeNodeCollection"></param>
        /// <param name="materials"></param>
        private void LoadTreeView(TreeNodeCollection treeNodeCollection, List<BOMType> BOMTypes)
        {
            if (BOMTypes != null && BOMTypes.Count > 0)
            {
                for (int i = 0; i < BOMTypes.Count; i++)
                {
                    TreeNode treeNode = treeNodeCollection.Add(BOMTypes[i].id.ToString(), BOMTypes[i].型号类别, 0, 1);
                    getAllBOMTypeByParentId(treeNode);
                    LoadTreeView(treeNode.Nodes, BOMTypes[i].Child);
                }
            }
        }

        /// <summary>
        /// 根据型号分类TreeNode的id查询具体型号
        /// </summary>
        /// <param name="node"></param>
        private void getAllBOMTypeByParentId(TreeNode node)
        {
            int parentId = Convert.ToInt32(node.Name);
            List<BOMModel> BOMModels = GetBOMModelBybomtypeId(parentId);
            LoadBOMModelTreeView(node.Nodes, BOMModels);
        }

        /// <summary>
        /// 根据Parentid查询所有型号
        /// </summary>
        /// <param name="bomtypeId"></param>
        /// <returns></returns>
        private List<BOMModel> GetBOMModelBybomtypeId(int bomtypeId)
        {
            List<BOMModel> BOMModels = SqlSugarHelp.scope.Queryable<BOMModel>().Where(it => it.bomtypeId == bomtypeId).OrderBy(it => it.序号).ToList();
            return BOMModels;
        }
        /// <summary>
        /// 加载具体型号
        /// </summary>
        /// <param name="treeNodeCollection"></param>
        /// <param name="BOMModels"></param>
        private void LoadBOMModelTreeView(TreeNodeCollection treeNodeCollection, List<BOMModel> BOMModels)
        {
            if (BOMModels != null && BOMModels.Count > 0)
            {
                for (int i = 0; i < BOMModels.Count; i++)
                {
                    TreeNode treeNode = treeNodeCollection.Add(BOMModels[i].id.ToString(), BOMModels[i].型号, 2, 2);
                    treeNode.Tag = "BOMModel";
                }
            }
        }
        #endregion

        private void tree_BOMType_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            //鼠标左键 只显示具体材料，不显示材料分类下的材料
            if (e.Button == MouseButtons.Left)
            {
                if (e.Node.Tag != null && e.Node.Tag.ToString() == "BOMModel")
                {
                   
                    CurrentNode = e.Node;
                    //清除之前的选中节点所查到的材料信息list
                    BOM_Material_MappingList.Clear();
                    //获取点击节点的 Name（数据的ID）
                    int BOMModelid = Convert.ToInt32(e.Node.Name);
                    //查询当前型号ID下的所有规格并组装成datatable
                    getBOMListByModelId(BOMModelid);

                }
            }
        }

        private void getBOMListByModelId(int bOMModelid)
        {
            DataTable BOMListDataTable = BOMService.getBOMListDataTableById(bOMModelid);
            
            bsBOMList.DataSource = BOMListDataTable;
            this.grid_BOMList.DataSource = bsBOMList;
            bsBOMList.ResetBindings(true);
            updateBOMListGridStyle();
            grid_BOMList.Refresh();
        }
        /// <summary>
        /// 会实时根据材料价格计算产品价格
        /// </summary>
        /// <param name="bOMModelid"></param>
        /// <param name="BOMListDataTable"></param>
        /// <returns></returns>
        //private void getBOMListByModelId(int bOMModelid)
        //{
        //    DataTable BOMListDataTable = BOMService.getBOMListDataTableById(bOMModelid);
        //    if (BOMListDataTable != null && BOMListDataTable.Rows.Count > 0)
        //    {
        //        //先把基础属性赋值到表格
        //        //grid_BOMList.DataSource = BOMListDataTable;
        //        //getBOMModel_MaterialHead(bOMModelid);
        //        //遍历规格，并读取其材料名称以及材料用量
        //        BOMListDataTable = getBOMModel_MaterialTable(bOMModelid, BOMListDataTable);
        //        //bsBOMList.Clear();
        //    }
        //    bsBOMList.DataSource = BOMListDataTable;
        //    this.grid_BOMList.DataSource = bsBOMList;
        //    bsBOMList.ResetBindings(true);
        //    updateBOMListGridStyle();
        //}

        private DataTable getBOMModel_MaterialTable(int bOMModelid, DataTable BOMListDataTable)
        {
            //根据bomModelId查询所需材料的信息
            BOM_Material_MappingList = BOMService.getMaterial(bOMModelid, 0);
            //根据查到的材料，加到规格表的表头
            foreach (BOM_Material_Mapping BOM_Material_Mapping in BOM_Material_MappingList)
            {
                //如果没有这个表头，就添加表头
                if (!BOMListDataTable.Columns.Contains(BOM_Material_Mapping.材料名称))
                {
                    //新增类型对应用料表的ID列
                    BOMListDataTable.Columns.Add(BOM_Material_Mapping.材料名称);
                }
            }
            //遍历型号表查询用量
            foreach (DataRow item in BOMListDataTable.Rows)
            {
                int bomListId = Convert.ToInt32(item["id"].ToString());
                decimal 材料成本 = 0;
                //根据查到的材料，加到规格表的表头
                foreach (BOM_Material_Mapping BOM_Material_Mapping in BOM_Material_MappingList)
                {
                    //根据型号id和规格id查询用量
                    int BOMModel_MaterialId = BOM_Material_Mapping.BOMModel_Material_Id;
                    int 材料id = BOM_Material_Mapping.material_Id;
                    //将用量赋值给行
                    decimal? dosage = BOMService.getMaterialDosage(bomListId, BOMModel_MaterialId, 材料id);
                    item[BOM_Material_Mapping.材料名称] = dosage;
                    //计算型号单价
                    //计算材料单价
                    decimal 偏移量 = 0;
                    decimal.TryParse(BOM_Material_Mapping.偏移量, out 偏移量);

                    decimal 材料单价 = BOM_Material_Mapping.材料单价 == null ? 0 : (decimal)BOM_Material_Mapping.材料单价 + 偏移量 / 1000;
                    材料成本 += (材料单价 * (dosage == null ? 0 : (decimal)dosage));
                }

                decimal 系数1 = 0;
                decimal 系数2 = 0;
                decimal 系数3 = 0;
                decimal.TryParse(item["系数1"].ToString(), out 系数1);
                decimal.TryParse(item["系数2"].ToString(), out 系数2);
                decimal.TryParse(item["系数3"].ToString(), out 系数3);
                //计算单价(元/米)
                item["单价"] = String.Format("{0:N3}", (材料成本 * (1 + 系数1) + 系数3) / 1000);
            }
            //this.grid_BOMList.DataSource = BOMListDataTable;
            return BOMListDataTable;
        }

        private void updateBOMListGridStyle()
        {
            //修改BOMList格式
            if (this.grid_BOMList.Rows.Count > 0)
            {
                grid_BOMList.Columns["选择"].Visible = false;
                grid_BOMList.Columns["选择"].Frozen = true;
                grid_BOMList.Columns["id"].Visible = false;
                grid_BOMList.Columns["id"].Frozen = true;
                grid_BOMList.Columns["bomModelId"].Visible = false;
                grid_BOMList.Columns["bomModelId"].Frozen = true;
                grid_BOMList.Columns["序号"].Frozen = true;
                grid_BOMList.Columns["序号"].DefaultCellStyle.BackColor = Color.LightGray;
                grid_BOMList.Columns["规格"].Frozen = true;
                //grid_BOMList.Columns["规格"].DefaultCellStyle.BackColor = Color.LightGray;
                grid_BOMList.Columns["单价"].Frozen = true;
                //grid_BOMList.Columns["单价"].DefaultCellStyle.BackColor = Color.LightGray;
                //grid_BOMList.Columns["系数1"].Visible = false;
                //grid_BOMList.Columns["系数2"].Visible = false;
                //grid_BOMList.Columns["系数3"].Visible = false;
                foreach (BOM_Material_Mapping BOM_Material_Mapping in BOM_Material_MappingList)
                {
                    grid_BOMList.Columns[BOM_Material_Mapping.材料名称].Visible = false;
                }
                //grid_BOMList.Columns["材料id"].Visible = false;
                grid_BOMList.EnableHeadersVisualStyles = false;
                grid_BOMList.ColumnHeadersDefaultCellStyle.BackColor = Color.LightGray;
            }
        }

        private void grid_BOMList_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataRowView a = (DataRowView)bsBOMList.Current;
            BOMSelected bOMSelected = new BOMSelected();
            bOMSelected.型号 = CurrentNode.Text;
            bOMSelected.规格 = a["规格"].ToString();
            //bOMSelected.数量 = a["数量"].ToString();
            bOMSelected.单价 = Convert.ToDecimal(a["单价"].ToString());
            bOMSelected.单位 = "米";
            //bOMSelected.型号 = a["小计金额"].ToString();
            BOMSelectedList.Add(bOMSelected);
            bsBOMSelectedList.DataSource = BOMSelectedList;
            this.dataGridView1.DataSource = bsBOMSelectedList;
            bsBOMSelectedList.ResetBindings(true);
            //显示序号
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                dataGridView1.Rows[i].Cells["D序号"].Value = i + 1;
            }
            dataGridView1.Refresh();
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            BOMSelected bOMSelected = (BOMSelected)bsBOMSelectedList.Current;
            bOMSelected.小计金额 = bOMSelected.数量.GetValueOrDefault() * bOMSelected.单价.GetValueOrDefault();
            bsBOMSelectedList.ResetBindings(true);
            //显示大写 合计
            decimal sum = 0;
            foreach (var item in BOMSelectedList)
            {
                sum += item.小计金额;
            }
            lab_合计.Text = sum.ToString("#0.00");
            lab_大写.Text = Pub.GetChinaMoney(sum);

            //for (int i = 0; i < dataGridView1.Rows.Count; i++)
            //{
            //    dataGridView1.Rows[i].Cells["D序号"].Value = i + 1;
            //}
        }

        private void buttonQuer_Click(object sender, EventArgs e)
        {
            Form_BOMListPriceHistoryManage form_BOMListPriceHistoryManage = new Form_BOMListPriceHistoryManage();
            form_BOMListPriceHistoryManage.ShowDialog();
        }

        private void Form_Main_Resize(object sender, EventArgs e)
        {
            //this.grid_BOMList.Width = splitContainer2.Panel2.Width - 10;
            //this.dataGridView1.Width = splitContainer2.Panel2.Width - 10;
        }

        private void dataGridView1_CellDoubleClick_1(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView1.BeginEdit(true);
        }

        private void dataGridView1_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
        {
            BOMSelected bOMSelected = (BOMSelected)bsBOMSelectedList.Current;
            bOMSelected.小计金额 = bOMSelected.数量.GetValueOrDefault() * bOMSelected.单价.GetValueOrDefault();
            bsBOMSelectedList.ResetBindings(true);
            //显示大写 合计
            decimal sum = 0;
            foreach (var item in BOMSelectedList)
            {
                sum += item.小计金额;
            }
            lab_合计.Text = sum.ToString("#0.00");
            labeldaxie.Text = Pub.GetChinaMoney(sum);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            bsBOMSelectedList.RemoveCurrent();
        }

        //上移
        private void button2_Click(object sender, EventArgs e)
        {
          int currentIndex =  bsBOMSelectedList.IndexOf(bsBOMSelectedList.Current);
            if (currentIndex > 0)
            {
                BOMSelected current = BOMSelectedList[currentIndex];
                BOMSelected up = BOMSelectedList[currentIndex - 1];
                BOMSelectedList.RemoveAt(currentIndex);
                BOMSelectedList.Insert(currentIndex,up);
                BOMSelectedList.RemoveAt(currentIndex - 1);
                BOMSelectedList.Insert(currentIndex -1,current);
                bsBOMSelectedList.ResetBindings(true);
                dataGridView1.Refresh();
                //dataGridView1.Rows[currentIndex - 1].Selected = true;
            }


        }
        //下移
        private void button3_Click(object sender, EventArgs e)
        {
            int currentIndex = bsBOMSelectedList.IndexOf(bsBOMSelectedList.Current);
            if (currentIndex < BOMSelectedList.Count - 1)
            {
                BOMSelected current = BOMSelectedList[currentIndex];
                BOMSelected down = BOMSelectedList[currentIndex + 1];
                BOMSelectedList.RemoveAt(currentIndex);
                BOMSelectedList.Insert(currentIndex, down);
                BOMSelectedList.RemoveAt(currentIndex + 1);
                BOMSelectedList.Insert(currentIndex + 1, current);
                bsBOMSelectedList.ResetBindings(true);
                dataGridView1.Refresh();
                //dataGridView1.sele
                //dataGridView1.Rows[currentIndex + 1].Selected = true;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    BOMSelectedList.Add(new BOMSelected { 单位 = "合计", 小计金额 = BOMSelectedList.Sum(it => it.小计金额) });
                    string foldPath = dialog.SelectedPath;
                    var path = Path.Combine(foldPath, $"{"报价单---" + DateTime.Now.ToString("yyyy-MM-dd mm")}.xlsx");
                    MiniExcel.SaveAs(path, BOMSelectedList);
                    MessageBox.Show("报价单导出成功");
                    BOMSelectedList.RemoveAt(BOMSelectedList.Count - 1);
                }
                catch (IOException ie)
                {
                    BOMSelectedList.RemoveAt(BOMSelectedList.Count - 1);
                    MessageBox.Show(ie.Message);
                }
            }
        }

        private void txt_notice_Click(object sender, EventArgs e)
        {
            Form_Notice form_Notice = new Form_Notice();
            form_Notice.ShowDialog();
        }

        private void button修改密码_Click(object sender, EventArgs e)
        {
            Form修改密码 form = new Form修改密码();
            form.ShowDialog(this);
        }

        private void button产品查询_Click(object sender, EventArgs e)
        {
            Form产品价格查询 f = new Form产品价格查询();
            f.选择产品 = 选择产品;
            f.Show();
        }

        public void 选择产品(string 型号, string 编码)
        {
            // 在TreeView控件中查找名为"NodeText"的节点
            TreeNode foundNode = FindNodeByText(tree_BOMType.Nodes, 型号);

            if (foundNode != null)
            {
                ClearNodeBackgroundColors(tree_BOMType.Nodes);
                tree_BOMType.CollapseAll();
                // 找到匹配的节点，可以在这里进行处理
                // 例如，选中节点、展开节点等
                tree_BOMType.SelectedNode = foundNode;
                tree_BOMType.SelectedNode.BackColor = System.Drawing.Color.Blue;
                foundNode.Expand();
                SelectRowByColumnValue(grid_BOMList, "编码", 编码);
            }
            else
            {
                // 没有找到匹配的节点
                MessageBox.Show("没有查到节点.");
            }

        }

        private void SelectRowByColumnValue(DataGridView dataGridView, string columnIndex, string value)
        {
            // 清除之前的选中行
            dataGridView.ClearSelection();

            // 遍历行，找到匹配的行并设置选中
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                if (row.Cells[columnIndex].Value != null && row.Cells[columnIndex].Value.ToString() == value)
                {
                    row.Selected = true;
                    dataGridView.FirstDisplayedScrollingRowIndex = row.Index;
                    break;
                }
            }
        }

        private TreeNode FindNodeByText(TreeNodeCollection nodes, string searchText)
        {
            foreach (TreeNode node in nodes)
            {
                if (node.Text == searchText)
                {
                    return node; // 找到匹配的节点
                }

                // 递归搜索子节点
                TreeNode foundNode = FindNodeByText(node.Nodes, searchText);

                if (foundNode != null)
                {
                    return foundNode; // 找到匹配的子节点
                }
            }

            return null; // 没有找到匹配的节点
        }

        private void ClearNodeBackgroundColors(TreeNodeCollection nodes)
        {
            foreach (TreeNode node in nodes)
            {
                node.BackColor = System.Drawing.Color.Empty; // 或者设置为TreeView控件的BackColor属性值
                ClearNodeBackgroundColors(node.Nodes); // 递归处理子节点
            }
        }

        private void tree_BOMType_AfterSelect(object sender, TreeViewEventArgs e)
        {
            CurrentNode = e.Node;
            //清除之前的选中节点所查到的材料信息list
            BOM_Material_MappingList.Clear();
            //获取点击节点的 Name（数据的ID）
            int BOMModelid = Convert.ToInt32(e.Node.Name);
            //查询当前型号ID下的所有规格并组装成datatable
            getBOMListByModelId(BOMModelid);
            //显示型号
            updateBOMListGridStyle();
        }

        private void grid_BOMList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
